<script setup>
import PCard from "@/components-mall/PCard";
import PList from "@/components-mall/PList";
import PComment from "@/components-mall/PComment";
import PImgList from "@/components-mall/PImgList";
import {
  getProductBySpu,
  getProductStatsInfo,
  collectProduct,
} from "@/api/mall/client/product";
import { delCollectSpu } from "@/api/mall/client/user/collect";
import { useRoute, useRouter } from "vue-router";
import { getCurrentInstance } from "vue";
import useCartStore from "@/store/modules/cart";

const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const product = ref({});
const spuFullReduction = ref({});
const getProductInfo = async () => {
  console.log("spuID", route.query.spuId);
  const res = await getProductBySpu(route.query.spuId);
  product.value = res.data;
  spuFullReduction.value = product.value.spuFullReduction;
  // 初始化form表单
  //  根据skuId找到对应的规格信息
  const sku = product.value.skuInfos.find(
    (item) => item.skuId == route.query.skuId
  );
  product.value.saleAttrConditions.forEach((item) => {
    item.attrValues = item.attrValues.split(",");
    let attr = null;
    if (sku) {
      attr = sku.attrs.find((e) => e.attrId == item.attrId);
      console.log("arrrr", attr);
    }
    form.value.saleAttrs.push({
      attrId: item.attrId,
      attrName: item.attrName,
      attrValue: sku ? attr.attrValue : item.attrValues[0],
    });
  });
  filterSkuInfo();
};
const imgBaseUrl = window.location.origin;
const form = ref({
  skuId: null,
  saleAttrs: [],
  num: 0,
});
// 库存信息
const inventory = ref({});
watch(
  () => form.value.skuId,
  (val) => {
    if (val) {
      getProductInfo()
      getProductStatsInfo(val).then((res) => {
        inventory.value = res.data;
      });
    }
  }
);
// 选择规格
const selectValue = (index, value) => {
  form.value.saleAttrs[index].attrValue = value;
  filterSkuInfo();
};
// 筛选sku信息
const skuInfo = ref({});
const filterSkuInfo = () => {
  const skuForm = [];
  form.value.saleAttrs.forEach((item) => {
    skuForm[item.attrId] = item.attrValue;
  });
  for (const sku of product.value.skuInfos) {
    if (sku.attrs.every((e) => skuForm.includes(e.attrValue))) {
      skuInfo.value = sku;
      form.value.skuId = skuInfo.value.skuId;
    }
  }
};

// 下单
const goPurchase = () => {
  router.push({
    path: "/purchase",
    query: {
      skuId: form.value.skuId,
      count: form.value.num,
    },
  });
};
// 添加购物车
const cartStore = useCartStore();
const goCart = async () => {
  const res = await cartStore.addCart(form.value);
  proxy.$modal.msgSuccess("添加购物车成功");
};
// 收藏商品
const addProductCollect = async () => {
  await collectProduct(product.value.spuId);
  getProductInfo();
  proxy.$modal.msgSuccess("收藏成功");
};
// 取消收藏
const removeProductCollect = async () => {
  await delCollectSpu(product.value.spuId);
  getProductInfo();
};
Promise.all([getProductInfo()]);
</script>
<template>
  <div class="product">
    <!-- 面包屑 -->
    <el-breadcrumb :separator-icon="ArrowRight" class="bread-crumb">
      <el-breadcrumb-item :to="{ path: '/' }">
        <el-icon><HomeFilled /></el-icon> 首页
      </el-breadcrumb-item>
      <el-breadcrumb-item
        :to="{ path: '/cate', query: { catalogId: product.catalogId } }"
        >{{ product.catName }}</el-breadcrumb-item
      >
      <el-breadcrumb-item>{{ product.spuName }}</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="product-card">
      <div class="prd-lf">
        <PImgList :imgList="skuInfo.skuImages" />
        <div class="actions">
          <el-button link icon="Share">分享</el-button>
          <el-button
            link
            icon="Star"
            v-show="!product.collected"
            @click="addProductCollect"
          >
            收藏</el-button
          >
          <el-button
            link
            v-show="product.collected"
            @click="removeProductCollect"
          >
            <el-icon
              icon=""
              color="#f7ba2a"
              :size="20"
              v-show="product.collected"
            >
              <StarFilled />
            </el-icon>
            收藏
          </el-button>
        </div>
      </div>
      <div class="prd-rt">
        <div class="prd-header">
          <h3 class="prd-title">{{ skuInfo.skuTitle }}</h3>
          <p class="prd-desc">{{ skuInfo.skuSubTitle }}</p>
        </div>
        <div class="prd-content">
          <div class="p-c-lf">
            <div class="sku-item">
              <div class="p-c-label">价格:</div>
              <div class="p-c-val red">￥{{ skuInfo.price }}</div>
            </div>
            <div class="sku-item">
              <div class="p-c-label">库存:</div>
              <div class="p-c-val">{{ inventory.stocked }}</div>
            </div>
            <div class="sku-item">
              <div class="p-c-label">运费:</div>
              <div class="p-c-val">包邮</div>
            </div>
            <div class="sku-item">
              <div class="p-c-label">满减优惠：</div>
              <div class="p-c-val">
                满
                <span style="color: #f56c6c; font-size: 16px">{{
                  spuFullReduction.fullPrice
                }}</span>
                减
                <el-tag type="danger" effect="dark" size="small"
                  >{{ spuFullReduction.reducePrice }} 元</el-tag
                >
              </div>
            </div>
            <div class="sku-item" v-if="product.spuDiscount">
              <div class="p-c-label">折扣：</div>
              <div class="p-c-val">
                满
                <span style="color: #f56c6c; font-size: 16px">{{
                  product.spuDiscount.fullCount
                }}</span>
                件
                <el-tag type="danger" effect="dark" size="small"
                  >{{ product.spuDiscount.discount * 10 }} 折</el-tag
                >
              </div>
            </div>
          </div>
          <div class="p-c-rt">
            <div class="total">
              <div class="total-item">
                <div class="t-label">累计评价</div>
                <div class="t-val">{{ product.commentCount }} 条</div>
              </div>
              <div class="total-item">
                <div class="t-label">累计销量</div>
                <div class="t-val">{{ inventory.saleCount }} 件</div>
              </div>
            </div>
          </div>
        </div>
        <div class="prd-sale-attr">
          <el-form>
            <el-form-item
              :label="item.attrName"
              v-for="(item, index) in product.saleAttrConditions"
              :key="item.attrId"
            >
              <div
                class="radio"
                :class="{
                  'is-active': form.saleAttrs[index].attrValue == value,
                }"
                v-for="value in item.attrValues"
                :key="value"
                @click="selectValue(index, value)"
              >
                {{ value }}
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="action">
          <el-input-number
            v-model="form.num"
            :min="1"
            controls-position="right"
            class="num-box"
          />
          <el-button icon="ShoppingCart" type="success" @click="goCart"
            >加入购物车</el-button
          >
          <el-button type="danger" @click="goPurchase">立即购买</el-button>
        </div>
      </div>
    </div>
    <div class="prd-container">
      <div class="prd-lf">
        <p-list></p-list>
      </div>
      <div class="prd-rt">
        <PCard title="商品详情">
          <el-descriptions :column="4" size="small">
            <el-descriptions-item label="品牌：">
              {{ product.brandName }}
            </el-descriptions-item>
            <el-descriptions-item
              v-for="attr in product.baseAttrs"
              :label="`${attr.attrName}：`"
              :key="attr.attrId"
            >
              {{ attr.attrValue }}
            </el-descriptions-item>
          </el-descriptions>
          <div class="info-text">
            {{ product.spuDescription }}
          </div>
          <!-- 图片 -->
          <div class="img-list">
            <img
              alt=""
              class="img"
              v-for="img in product.spuImageList"
              :src="imgBaseUrl + img.imageUrl"
              :key="img.id"
            />
          </div>
        </PCard>
        <p-comment :spuId="product.spuId" />
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.prd-sale-attr {
  margin-top: 10px;
  :deep(.el-form-item--default) {
    margin-bottom: 10px;
  }
}
.radio {
  padding: 0 10px;
  position: relative;
  margin-right: 5px;
  font-size: 14px;
  border: 1px solid #e9e9e9;
}
.is-active {
  border: 1px solid #1aa684;
  position: relative;
  overflow: hidden;
  &::before {
    content: "√";
    position: absolute;
    right: -10px;
    bottom: 5px;
    width: 50%;
    height: 50%;
    color: #fff;
    z-index: 22;
    font-size: 12px;
  }
  &::after {
    content: "";
    position: absolute;
    right: 0;
    bottom: -15px;
    border-top: 20px solid transparent;
    border-right: 30px solid #1aa684;
    border-bottom: 15px solid transparent;
    width: 0;
    height: 0;
    text-align: center;
  }
}
.product {
  padding-bottom: 20px;
}
.bread-crumb {
  padding: 20px 0;
  --el-color-primary: #1aa684;
}
.product-card {
  padding: 20px;
  background: #fff;
  display: flex;

  .prd-lf {
    width: 35%;
    .actions {
      margin-top: 20px;
      // .el-button {
      // 	color: #1aa684;
      // }
    }
  }
  .prd-rt {
    flex: 1;
    .prd-header {
      .prd-title {
        color: #1aa684;
        font-weight: 700;
        font-size: 22px;
      }
      .prd-desc {
        color: rgb(156 163 175);
        font-size: 14px;
        padding: 10px 0;
      }
    }
    .prd-content {
      padding: 20px 10px;
      background: #e9e9e9;
      display: flex;
      .p-c-lf {
        width: 60%;
        font-size: 14px;
        .sku-item {
          display: flex;
          align-items: flex-end;
          padding: 6px 0;
          .p-c-label {
            margin-right: 5px;
          }
        }
      }
      .p-c-rt {
        flex: 1;
        .total {
          display: flex;
          justify-content: flex-end;
          padding-right: 20px;
          .total-item {
            margin-right: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            .t-label {
              color: #1aa684;
              font-weight: 600;
              padding-bottom: 5px;
            }
          }
        }
      }
    }
    .action {
      margin-top: 10px;
      .el-input-number {
        width: 80px;
        margin-right: 15px;
        :deep(.is-focus) {
          box-shadow: 0 0 0 1px #1aa684 inset;
        }
        :deep(.el-input-number__decrease) {
          &:hover {
            color: #1aa684;
          }
        }
        :deep(.el-input-number__increase) {
          &:hover {
            color: #1aa684;
          }
        }
      }
    }
  }
}
.prd-container {
  margin-top: 15px;
  display: flex;
  .prd-lf {
    width: 30%;
    padding-right: 10px;
  }
  .prd-rt {
    flex: 1;
    .info-text {
      color: #666;
      padding: 10px 0;
      line-height: 30px;
      text-indent: 2em;
    }
    .img-list {
      border-top: 1px solid #e9e9e9;
      padding-top: 10px;
      height: 100%;
      .img {
        width: 800px;
        height: 800px;
        object-fit: cover;
        margin: 0;
        // 图片不是紧贴着div的，要加上block,不然有间隙
        display: block;
      }
    }
  }
}
</style>
